package com.tuniu.agents.common;

import io.micrometer.common.util.StringUtils;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.SimpleLocaleContext;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class CustomLocaleContextHolder {
    
    // Cache to hold locale contexts with a 1-day expiration
    private static final Cache<String, LocaleContext> localeContextCache = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.DAYS)
            .build();

    // Set the locale context for a given ID
    public static void setLocaleContext(String localeContextId, LocaleContext localeContext) {
        localeContextCache.put(localeContextId, localeContext);
    }

    // Get the locale context for a given ID
    public static LocaleContext getLocaleContext(String localeContextId) {
        return localeContextCache.getIfPresent(localeContextId);
    }

    // Set the locale for a given ID
    public static void setLocale(String localeContextId, Locale locale) {
        setLocaleContext(localeContextId, new SimpleLocaleContext(locale));
    }

    // Get the locale for a given ID
    public static Locale getLocale(String localeContextId) {
        Locale locale = null;
        if (StringUtils.isNotEmpty(localeContextId)) {
            LocaleContext localeContext = getLocaleContext(localeContextId);
            if (localeContext != null) {
                locale = localeContext.getLocale();
            }
        }
        return locale;
    }

    // Reset the locale context for a given ID
    public static void resetLocaleContext(String localeContextId) {
        localeContextCache.invalidate(localeContextId);
    }

    // Clean up expired locale contexts
    public static void cleanExpiredLocaleContexts() {
        localeContextCache.cleanUp();
    }
}